<?php

class Database_Mysqli_Exception extends Database_Exception {
	private $_mysqli_code;
	public function __construct($message, $mcode){
		$this->_mysqli_code = $mcode;
		parent::__construct("{$message} ({$mcode})");
	}
}

class Database_Mysqli_Connect_Exception extends Database_Mysqli_Exception {}

class Database_Mysqli_Query_Exception extends Database_Mysqli_Exception {
	private $_query;
	private $_sql;
	public function __construct($message, $mcode, $query, $sql){
		$this->_query = $query;
		$this->_sql = $sql;
		parent::__construct("$message ('{$query}' => '{$sql}')", $mcode);
	}
}

class Database_Mysqli extends mysqli implements IDatabase {

	public function __construct($config){
		parent::__construct($config['host'],$config['user'],$config['password'],$config['database'],$config['port'],$config['socket']);
		if(mysqli_connect_error()){
			throw new Database_Mysqli_Connect_Exception(mysqli_connect_error(), mysqli_connect_errno());
		}
	}

	public function escape($string){
		if(is_numeric($string)){
			return $string;
		}
		if(is_bool($string)){
			return (bool) $string;
		}
		$var = '"' . $this->escape_string($string) . '"';
		return $var;
	}

	public function query($query){
		$args = func_get_args();
		array_shift($args);
		$args = array_map(array($this, 'escape'), $args);

		$sql = vsprintf($query, $args);
		if(!($result = parent::query($sql))){
			throw new Database_Mysqli_Query_Exception($this->error, $this->errno, $query, $sql);
		}
		return $result;
	}



}
